from . import webs
from web.model.questionnaire_model import Questionnaire, Question, Options, Completed, Completion
from web.model.user_model import User
from web.control.verification.message_forms import *
from web.control.route.func import *
from web.control.error.error_code import Success, SQLException, RootException
from ...model.base_model import db
from flask_cors import cross_origin


@webs.route('/questionnaire/', methods=['POST', 'GET', 'DELETE', 'PUT'])
def new_questionnaire():
    """
    问卷表的增删改查

    :return: 成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(Questionnaire, QuestionnaireForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(Questionnaire, get_args('id'))
        return Success(data=Questionnaire.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(Questionnaire, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        data = query_by_id(Questionnaire, get_args('id'))
        return data.delete()


@webs.route('/question/', methods=['POST', 'GET', 'DELETE', 'PUT'])
def new_question():
    """
    问题的增删改查

    :return: 成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(Question, QuestionForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(Question, get_args('id'))
        return Success(data=Question.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(Question, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        id = get_args('id')
        option_data = Options.query.filter(Options.questionId == id)
        for i in option_data:
            i.delete()
        data = query_by_id(Question, id)
        return data.delete()


@webs.route('/options/', methods=['POST', 'GET', 'DELETE', 'PUT', 'PATCH'])
def new_options():
    """
    问题对应选项的增删改查

    :return: 成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(Options, OptionsForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(Options, get_args('id'))
        return Success(data=Options.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(Options, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        data = query_by_id(Options, get_args('id'))
        return data.delete()
    elif request.method == 'PATCH':
        data = query_by_id(Options, get_args('id'))
        try:
            data.count += 1
            db.session.commit()
        except Exception as error:
            raise SQLException(msg=error)
        return Success(msg='')


@webs.route('/Completed/', methods=['POST', 'GET', 'DELETE', 'PUT'])
def new_completed():
    """
    已填问卷情况表的增删改查

    :return:成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(Completed, CompletedForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(Completed, get_args('id'))
        return Success(data=Completed.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(Completed, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        data = query_by_id(Completed, get_args('id'))
        return data.delete()


@webs.route('/User/', methods=['POST', 'GET', 'DELETE', 'PUT'])
def new_user():
    """
    用户表的增删改查

    :return:成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(User, UserForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(User, get_args('id'))
        return Success(data=User.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(User, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        data = query_by_id(User, get_args('id'))
        return data.delete()


@webs.route('/Completion/', methods=['POST', 'GET', 'DELETE', 'PUT'])
def new_completion():
    """
    填空题表的增删改查

    :return:成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST':
        return assignment(Completion, CompletedForm, get_json()).add()
    elif request.method == 'GET':
        data = query_by_id(Completion, get_args('id'))
        return Success(data=Completion.query_data(data), msg="查询成功")
    elif request.method == 'PUT':
        data = query_by_id(Completion, get_args('id'))
        return data.put(get_json())
    elif request.method == 'DELETE':
        data = query_by_id(Completion, get_args('id'))
        return data.delete()


@webs.route('/commit/', methods=['POST', 'Options'])
@cross_origin(supports_credentials=True)
def commit_questionnaire():
    """
    用户填写完问卷之后的提交，该接口实现了选项数据的添加，以及用户是否填写过该表的校验

    :return:成功则返回请求对应的数据或提示性信息，报错则返回相应的异常信息
    """
    if request.method == 'POST' or request.method == 'Options':
        json = get_json()
        json_data = json['res']
        user_dict = {
            'userId': json['userid'],
            'questionnaireId': json['questionnaireid']
        }
        if Completed.query.filter(Completed.userId == user_dict['userId'],
                                  Completed.questionnaireId == user_dict['questionnaireId']).first():
            return RootException(msg='不可重复提交')
        for data in json_data:
            if data['type'] == 1:
                commit_option(Options, data['answer'])
            elif data['type'] == 2:
                for id in data['answer']:
                    commit_option(Options, id)
            elif data['type'] == 3:
                user_dict['context'] = data['answer']
                user_dict['questionId'] = data['id']
                assignment(Completion, CompletionForm, user_dict).add()
        return assignment(Completed, CompletedForm, user_dict).add()
